package dao

import (
	"context"
	"system-admin/internal/app/grpc/client"
	"system-admin/internal/app/grpc/protoc/devicec"
	"system-admin/internal/dal"
	"system-admin/internal/models"

	"192.168.1.75/go-pkg/errorx"
)

type TempDevice struct{}

// CreateTempDevice 创建设备临时表，包含设备id及省市区信息
// 在通过grpc获取数据，并填充
func (TempDevice) CreateTempDevice(ctx context.Context, tx *dal.Query) error {
	// 创建临时表
	err := tx.TempDevice.WithContext(ctx).UnderlyingDB().Exec(`
		CREATE TEMPORARY TABLE  IF NOT EXISTS temp_device (
			robot_id VARCHAR(40) COMMENT '设备id',
			province_id bigint COMMENT '省份',
			city_id bigint COMMENT '城市',
			district_id bigint COMMENT '区县',
			location_id bigint COMMENT '位置',
			merchant_id bigint COMMENT '商户id',
			merchant_path VARCHAR(200) COMMENT '商户路径',
			PRIMARY KEY (robot_id) USING BTREE
		)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
	`).Error
	if err != nil {
		return errorx.New("create temp-device failed", -1)
	}
	// 获取设备服务grpc客户端
	deviceServiceCli, err := client.GetDeviceAdminClient()
	if err != nil {
		return errorx.New("省市区信息获取失败", -1)
	}
	// 获取设备列表
	rsp, err := deviceServiceCli.DeviceList(context.Background(), &devicec.DeviceListReq{})
	if err != nil || rsp.Code != 0 {
		return errorx.New("设备列表获取失败", -1)
	}
	// 临时表插入数据
	tempDeviceRecords := []*models.TempDevice{}
	for _, device := range rsp.List {
		// 忽略返厂的机器
		if device.MerchantId == "1" || device.MerchantId == "0" {
			continue
		}
		if device.ProvinceId == "" {
			device.ProvinceId = "0"
		}
		if device.CityId == "" {
			device.CityId = "0"
		}
		if device.DistrictId == "" {
			device.DistrictId = "0"
		}
		if device.LocationId == "" {
			device.LocationId = "0"
		}
		tempDeviceRecords = append(tempDeviceRecords, &models.TempDevice{
			RobotID:      device.RobotId,
			ProvinceID:   device.ProvinceId,
			CityID:       device.CityId,
			DistrictID:   device.DistrictId,
			LocationID:   device.LocationId,
			MerchantID:   device.MerchantId,
			MerchantPath: device.MerchantPath,
		})
	}
	// grpc调用数据，填充临时表
	tx.TempDevice.WithContext(ctx).CreateInBatches(tempDeviceRecords, 300)
	return nil
}

// DropTempDevice 释放临时表
func (TempDevice) DropTempDevice(ctx context.Context, tx *dal.Query) error {
	tx.TempDevice.WithContext(ctx).UnderlyingDB().Exec(`DROP TABLE IF EXISTS temp_device;`)
	return nil
}
